<template>
  <van-popup class="code-popup" v-model="showCode" :close-on-click-overlay="false">
    <div class="verification-code">
      <div class="code-alert">
        {{$t('varification_code_tip')}}
      </div>
      <div class="code-content">
        <div style="display:flex;" class="code">
          <img :src="'data:image/jpg;base64,' + code">
          <div class="refresh-code" @click="getCode">{{$t('refresh_code')}}</div>
        </div>
        <div class="tip">{{$t('enter_code')}}</div>
        <van-password-input
          :value="usrEnter"
          :mask="false"
          :length="4"
          :gutter="10"
          :error-info="errorInfo"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
      </div>
      <div class="footer">
        <van-button class="sm-bt-BU comment-submit" @click="sureCode">{{$t('mall_10')}}</van-button>
        <div class="close-tip">{{$t('close_tip', {time: times})}}</div>
      </div>
      <!-- 数字键盘 -->
        <van-number-keyboard class="key-bored" v-if="showKeyboard"
          theme="custom"
          z-index="9999"
          :close-button-text="$t('mall_10')"
          :get-container="getContainer"
          v-model="usrEnter"
          :show="showKeyboard"
          @blur="showKeyboard = false"
        />
    </div>
  </van-popup>
</template>

<script>
import {Toast} from 'vant';
export default {
    name: 'verification-code',
    components: {
        Toast
    },
    data() {
        return {
            showCode: true,
            code: '',
            times: 30,
            count: 0,
            isStart: false,
            startTime: '',
            usrEnter: '',
            timer: {},
            setTimer: {},
            showKeyboard: false,
            errorInfo: '',
            uuid: '' // 随机值
        };
    },
    created() {
    },
    mounted() {
        this.getCode();
    },
    methods: {
        // 返回一个特定的 DOM 节点，作为挂载的父节点
        getContainer() {
            return document.querySelector('.content-noBottom');
        },
        getCode() {
            this.$axios({
                method: 'GET',
                url: `/app/api/captcha/getCaptchaCode`
            }).then(res => {
                if (res) {
                    // 修改了接口，图片改为res.data.image字段非原本的res.data，适配APP端。
                    this.code = res.data.image;
                    this.uuid = res.data.uuid;
                    if (!this.isStart) {
                        this.isStart = true;
                        this.startTimeOut();
                    }
                }
            });
        },
        // 确认提交验证码
        postCode() {
            if (!this.usrEnter) {
                Toast.fail(this.$t('error14'));
                return;
            }
            this.$axios({
                method: 'GET',
                url: `/app/api/captcha/checkCaptchaCode/${this.usrEnter}`,
                // 添加uuid参数
                params: {
                    uuid: this.uuid
                }
            }).then(res => {
                if (res) {
                    // clearInterval(this.timer);
                    clearTimeout(this.setTimer);
                    const times = 30 - this.times;
                    this.$emit('pass-code', times);
                }
            }).catch((error) => {
                if (error.response) {
                    this.errorInfo = error.response.data.errMsg;
                } else if (error.request) {
                    this.errorInfo = error.request.data.errMsg;
                } else {
                    this.errorInfo = error.message.data.errMsg;
                }
            });
        },
        /**
         * @description: 确认提交验证码
         * @param {*}
         * @return {*}
         */
        sureCode() {
            this.postCode();
        },
        /**
         * @description: 关闭弹窗倒计时
         * @param {*}
         * @return {*}
         */
        startTimeOut() {
            this.startTime = new Date().getTime();
            this.count = 0;
            // this.timer = setInterval(function() {
            //     var i = 0;
            //     while (i++ < 100000000);
            // }, 0);
            this.setTimer = setTimeout(this.fixed, 1000);
            this.$once('hook:beforeDestroy', () => {
                // clearInterval(this.timer);
                clearTimeout(this.setTimer);
            });
        },
        fixed() {
            this.count++;
            this.times--;
            var offset = new Date().getTime() - (this.startTime + this.count * 1000);
            var nextTime = 1000 - offset;
            if (nextTime < 0) nextTime = 0;
            if (this.times === 0) {
                this.showKeyboard = false;

                // clearInterval(this.timer);
                clearTimeout(this.setTimer);
                this.$emit('overtime-code');
            } else {
                this.setTimer = setTimeout(this.fixed, nextTime);
            }
        }
    },
    beforeDestroy() {
        this.showKeyboard = false;
    }
};
</script>

<style scoped lang="less">
.verification-code{
  // width: 80%;
  padding: 15px;
}
.code-alert{
  color: #999;
  line-height: 20px;
  text-indent: 2em;
}
.code-content{
  margin-top:30px;
  .code{
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 10px 0;
    img{
      margin: 0 10px;
    }
  }
  .tip{
    color: #999;
    text-align: center;
  }
  .refresh-code{
    color: #999;
    cursor: pointer;
    text-align: center;
    &:hover{
      text-decoration: underline;
    }
  }
}
.footer{
  text-align: center;
  margin-top:20px;
  position: relative;
  .comment-submit{
    margin-right: 10px;
  }
  .close-tip{
    // position: absolute;
    // line-height: 40px;
    color: #999;
    margin-top: 10px;
  }
}
/deep/.van-password-input__security li{
  border-bottom: 1px solid #999;
}
/deep/.van-key--blue{
  background-color: #075ebb;
}
</style>
